package com.atguigu.gmall.user.controller;


import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.IpUtil;
import com.atguigu.gmall.model.user.UserInfo;
import com.atguigu.gmall.user.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Api(tags = "用户控制器")
@RestController
@RequestMapping("api/user/passport")//前端已经写好
public class PassportApiController {
    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;

    @ApiOperation("用户登录")
    @PostMapping("login")
    public Result login(@RequestBody UserInfo userInfo, HttpServletRequest request){
        UserInfo info = userService.login(userInfo);
        if (info != null){
            //生成token
            String token = UUID.randomUUID().toString();
            //向redis中存入数据 用户id 及ip
            String userKey = RedisConst.USER_LOGIN_KEY_PREFIX+token;
            String ipAddress = IpUtil.getIpAddress(request);

            System.out.println("ipAddress = " + ipAddress);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("id",info.getId().toString());
            jsonObject.put("ip",ipAddress);
            redisTemplate.opsForValue().set(userKey,jsonObject.toJSONString(),RedisConst.USERKEY_TIMEOUT, TimeUnit.SECONDS);

            String nickName = info.getNickName();
            HashMap<Object, Object> hashMap = new HashMap<>();
            hashMap.put("token",token);
            hashMap.put("nickName",nickName);
            return Result.ok(hashMap);
        }

        return Result.fail().message("用户名或密码错误");
    }

    @ApiOperation("用户登出")
    @GetMapping("logout")
    public Result logout(HttpServletRequest request){
        String token = request.getHeader("token");
        String userKey = RedisConst.USER_LOGIN_KEY_PREFIX + token;
        redisTemplate.delete(userKey);
        return Result.ok();

    }

}
